package cn.edu.ujn.lab1.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.ujn.lab1.model.User;

@Repository
@Transactional
public class UserDaoImpl implements IUserDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	

	public User addUser(User user) {
		// TODO 自动生成的方法存根
		String sql = "insert into user(username,password) values(?,?)";
		GeneratedKeyHolder holder = new GeneratedKeyHolder();
		
		int update = this.jdbcTemplate.update(new PreparedStatementCreator() {
			
			@Override
			public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
				// TODO 自动生成的方法存根
				PreparedStatement ps = con.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
				ps.setString(1, user.getUsername());
				ps.setString(2, user.getPassword());
				
				return ps;
			}
		}, holder);
		if(update>0) {
			int intValue = holder.getKey().intValue();
			user.setUid(intValue);
			return user;
		}return null;
	}

	public List<User> findAllUser() {
		// TODO 自动生成的方法存根
		String sql="select * from user";
		BeanPropertyRowMapper<User> mapper = new BeanPropertyRowMapper<User>(User.class);
		return this.jdbcTemplate.query(sql, mapper);
	}

	@Override
	public int updateUser(User user) {
		// TODO 自动生成的方法存根
		String sql="update user set username=?,password=? where uid=?";
		Object[] params=new Object[] {user.getUsername(),user.getPassword(),user.getUid()};
		int num=this.jdbcTemplate.update(sql,params);
		return num;
	}

	@Override
	public int deleteUser(int id) {
		// TODO 自动生成的方法存根
		String sql="delete from user where uid=?";
		int num=this.jdbcTemplate.update(sql,id);
		return num;
	}

}
